package com.sheep.spark.rest;

import com.sheep.spark.util.ConfSupport;
import com.sheep.spark.util.SparkSupport;
import com.sun.jersey.spi.container.servlet.ServletContainer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Administrator on 2016/1/22.
 */
public class JettyService {

    public static final Logger log = LoggerFactory.getLogger(JettyService.class);

    public static Server jettyServer = null;
    private static String contextPath = "/";

    public static void start() throws Exception {
        start(ConfSupport.getConfig().getInt("jetty.port", 8899));
    }

    public static void start(int port) throws Exception {
        try {
            if (log.isInfoEnabled()) {
                log.info("OpenPlatformNotifyService initializing");
            }
            initWebservice(port);
        } catch (Exception e) {
            log.error("start error:", e);
        }
    }

    private static void initWebservice(int port) throws Exception {
        log.info("start init jetty service...");
        jettyServer = new Server(port);
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath(contextPath);
        jettyServer.setHandler(context);
        ServletHolder sh = new ServletHolder(ServletContainer.class);
        sh.setInitParameter("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig");
        sh.setInitParameter("com.sun.jersey.config.property.packages", "com.sheep.spark.rest.service");

        context.addServlet(sh, "/*");
        jettyServer.start();
    }

    public void stop() throws Exception {
//        jettyServer.stop();
    }

    public static void main(String[] args) throws Exception {
        SparkSupport.init();
        JettyService server = new JettyService();
        server.start();
    }
}